//
//  NetworkTools.swift
//  weibosina
//
//  Created by 李明禄 on 15/10/10.
//  Copyright © 2015年 李明禄. All rights reserved.
//

import UIKit
import AFNetworking

class NetworkTools: AFHTTPSessionManager {
    
    //设计一个单例
    static let sharedTools: NetworkTools = {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        let tools = NetworkTools(baseURL: baseURL)
        // 设置数据解析数据类型
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        
        return tools
        
    }()
    
//  MARK:  oAuth
    
    let clientId = "3123639654"
    let appSecret = "7a1010a34ac579cf8cc5c9a1b636cbfa"
    
    //回调地址
    let redirectUri = "http://www.baidu.com"
    
//    返回oAuth的授权地址
    
    func oauthUrl() -> NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    
    
///  加载token
    //https://www.baidu.com/?code=6f473d0c9c3fe5cb196fbcf1ff0cacee
    /// 加载 Token
    func loadAccessToken(code: String, finished: (result: [String: AnyObject]?, error: NSError?)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        
        // 测试代码-设置返回的数据格式
         responseSerializer = AFHTTPResponseSerializer()
        
        POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            // {"access_token":"2.00ml8IrFX6ZhGE09ce0ebf870fPkb1","remind_in":"157679999","expires_in":157679999,"uid":"5365823342"}
            // 没有引号的值在反序列化的时候，会变成 NSNumber
            // print(NSString(data: JSON as! NSData, encoding: NSUTF8StringEncoding))
            
            finished(result: JSON as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
                print(error)
                finished(result: nil, error: error)
        }
    }

}
